package github.sf.fw.tools.serializer;

import com.google.gson.*;

import java.lang.reflect.Type;

/**
 * ConstraintDesc使用Gson的反序列化类
 * example:
 * <pre>
 *         String s = Jsons.Gson.toPrettyJson(new ImplementMarkerImpl());
 *         System.out.println(s);
 *         Gson gson = new GsonBuilder()
 *                 .registerTypeAdapter(ConstraintDesc.class, new ImplGsonDeserializer())
 *                 .create();
 *         ImplementMarker impl = gson.fromJson(s, ImplementMarker.class);
 *         System.out.println("new ImplementMarker");
 *         System.out.println(Jsons.Gson.toPrettyJson(impl));
 * </pre>
 */
public class ImplGsonDeserializer implements JsonDeserializer<ImplementMarker> {
    private final ImplContainer implContainer;
    private final Gson gson = new GsonBuilder().create();

    public ImplGsonDeserializer() {
        this.implContainer = ImplContainer.getInstance();
    }

    @Override
    public ImplementMarker deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        if (!jsonElement.isJsonObject()) {
            return null;
        }
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        String constraintType = safeGetAsString(jsonObject, ImplementMarker.ImplTypeProperty);
        Class<? extends ImplementMarker> clazz = implContainer.resolveClass(constraintType);
        return gson.fromJson(jsonElement, clazz);
    }


    private String safeGetAsString(JsonObject jsonObject, String memberName) {
        JsonElement jsonElement = jsonObject.get(memberName);
        if (isValid(jsonElement)) {
            return jsonElement.getAsString();
        }
        return null;
    }

    private boolean isValid(JsonElement jsonElement) {
        return jsonElement != null && jsonElement.isJsonPrimitive();
    }
}
